package com.cumt.threeway.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.cumt.threeway.R;
import com.cumt.threeway.activity.CheckSubmitActivity;
import com.cumt.threeway.activity.FavouriteActivity;
import com.cumt.threeway.activity.LoginActivity;
import com.cumt.threeway.activity.MyStrategyActivity;
import com.cumt.threeway.activity.PersonInfoActivity;
import com.cumt.threeway.activity.SettingActivity;
import com.cumt.threeway.constant.ThreeWayConstant;
import com.cumt.threeway.model.User;
import com.cumt.threeway.util.ThreeWayUtil;
import com.cumt.threeway.view.dialog.NeedLoginDialog;
import com.cumt.threeway.view.widget.CircleImageView;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * Created by Jingjing.Hu on 2016/4/1.
 */
public class MyFragment extends Fragment implements View.OnClickListener {

    private final int REQUEST_CODE_FOR_CAMERA = 1;
    private final int REQUEST_CODE_FOR_GALLERY = 2;
    private final int REQUEST_CODE_FOR_LOGIN = 3;
    private File mCurrentPhotoFile = null;// 拍照得到的图片
    private CircleImageView mAvatarImageView;
    private View mGongLueView;
    private View mFavoriteView;
    private View mRegisterView;
    private View mSettingView;
    private TextView mTvUserName;
    private String mPath;
    private User mUser;
    private Bitmap mBitmap;
    private String mUserAccount;
    private String mUserName;

    public static MyFragment newInstance() {
        return new MyFragment();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mTvUserName.setText(mUser.getName());
                    mAvatarImageView.setImageBitmap(mBitmap);
                    ThreeWayUtil.getInstance().saveUserName(getActivity(), mUser.getName());
                    ThreeWayUtil.getInstance().saveThirdUserName(getActivity(), mUser.getName());
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_layout, null, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        view.findViewById(R.id.iv_head).setOnClickListener(this);
        view.findViewById(R.id.rl_gonglue).setOnClickListener(this);
        mUserAccount = ThreeWayUtil.getInstance().getLoginAccount(getActivity());
        mUserName = ThreeWayUtil.getInstance().getUserName(getActivity());
        mGongLueView = view.findViewById(R.id.rl_gonglue);
        mFavoriteView = view.findViewById(R.id.rl_wodeshoucang);
        mRegisterView = view.findViewById(R.id.rl_wodebaoming);
        mSettingView = view.findViewById(R.id.rl_shezhi);
        mAvatarImageView = (CircleImageView) view.findViewById(R.id.iv_head);
        mTvUserName = (TextView) view.findViewById(R.id.tv_name);
        mTvUserName.setText(mUserName);

        mRegisterView.setOnClickListener(this);
        mFavoriteView.setOnClickListener(this);
        mGongLueView.setOnClickListener(this);
        mSettingView.setOnClickListener(this);

        if(!TextUtils.isEmpty(mUserAccount)) {
            mPath = ThreeWayConstant.PATH + mUserAccount + "head.jpg";
            Bitmap bitmap = ThreeWayUtil.getInstance().createChangedImage(mPath);
            if(bitmap != null) {
                mAvatarImageView.setImageBitmap(bitmap);
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v == null) {
            return;
        }
        switch (v.getId()) {
            case R.id.iv_head:
                if(!TextUtils.isEmpty(ThreeWayUtil.getInstance().getLoginAccount(getActivity()))) {
                    goPersonInfoActivity();
                } else {
                    goLoginActivity();
                }
                break;
            case R.id.rl_gonglue:
                if(!TextUtils.isEmpty(ThreeWayUtil.getInstance().getLoginAccount(getActivity()))) {
                    goMyStrategyActivity();
                } else {
                    goLoginActivity();
                }
                break;
            case R.id.rl_wodebaoming:
                if(!TextUtils.isEmpty(ThreeWayUtil.getInstance().getLoginAccount(getActivity()))) {
                    goCheckSubmitActivity();
                } else {
                    NeedLoginDialog needLoginDialog = NeedLoginDialog.newInstance("checkSubmitInfo");
                    needLoginDialog.show(getFragmentManager(),"needLoginDialog");
                }
                break;
            case R.id.rl_wodeshoucang:
                goFavouriteActivity();
                break;
            case R.id.rl_shezhi:
                goSettingActivity();
                break;
        }
    }

    private void goSettingActivity() {
        Intent intent = new Intent(getActivity(), SettingActivity.class);
        startActivity(intent);
    }

    private void goFavouriteActivity() {
        Intent intent = new Intent(getActivity(), FavouriteActivity.class);
        startActivity(intent);
    }

    private void goCheckSubmitActivity() {
        Intent intent = new Intent(getActivity(), CheckSubmitActivity.class);
        startActivity(intent);
    }

    private void goMyStrategyActivity() {
        Intent intent = new Intent(getActivity(), MyStrategyActivity.class);
        startActivity(intent);
    }

    private void goLoginActivity() {
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        getActivity().startActivityForResult(intent, REQUEST_CODE_FOR_LOGIN);
    }

    private void goPersonInfoActivity() {
        Intent intent = new Intent(getActivity(), PersonInfoActivity.class);
        getActivity().startActivityForResult(intent, ThreeWayConstant.REQUEST_CODE_FOR_LOGIN);
    }

    public void setThirdLoginUserInfo(User user) {
        if(user != null) {
            mUser = user;
            MyImgThread imgThread = new MyImgThread(user.getImagePath());
            Thread thread = new Thread(imgThread);
            thread.start();
        }
    }

    public void setUserInfo(User user) {
        if(user != null) {
            mUser = user;
            mTvUserName.setText(mUser.getName());
            ThreeWayUtil.getInstance().saveUserName(getActivity(), mUser.getName());
        }
    }

    public void setUserIco() {
        mUserAccount = ThreeWayUtil.getInstance().getLoginAccount(getActivity());
        mUserName = ThreeWayUtil.getInstance().getUserName(getActivity());
        mTvUserName.setText(mUserName);
        if(!TextUtils.isEmpty(mUserAccount)) {
            mPath = ThreeWayConstant.PATH + mUserAccount + "head.jpg";
            Bitmap bitmap = ThreeWayUtil.getInstance().createChangedImage(mPath);
            if(bitmap != null) {
                mAvatarImageView.setImageBitmap(bitmap);
            }
        }
    }

    /**
     * 开启线程 获取头像
     */
    class MyImgThread implements Runnable {
        private String imgPath;

        public MyImgThread(String imgpath) {
            this.imgPath = imgpath;
        }

        @Override
        public void run() {
            // TODO Auto-generated method stub
            mBitmap = getImgBitmap(imgPath);
            Message msg = new Message();
            msg.obj = mBitmap;
            msg.what = 1;
            mHandler.sendMessage(msg);
        }
    }

    /**
     * 根据头像的url 获取bitmap
     */
    public Bitmap getImgBitmap(String imageUri) {
        // 显示网络上的图片
        Bitmap bitmap = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        try {
            if(!TextUtils.isEmpty(imageUri)) {
                URL myFileUrl = new URL(imageUri);
                conn = (HttpURLConnection) myFileUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();

                is = conn.getInputStream();
                bitmap = BitmapFactory.decodeStream(is);
                String path = ThreeWayConstant.PATH +  mUser.getAccount() + "head.jpg";
                ThreeWayUtil.getInstance().savePicture(path, bitmap);
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                conn.disconnect();
                is.close();
                is.reset();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return bitmap;
    }
}
